﻿using B.S.BasicData.API.Read.Application.Command;
using B.S.BasicData.API.Read.DTOS;
using B.S.BasicData.Common;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MD5Hash;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace B.S.BasicData.API.Read.Application.Handler
{
    /// <summary>
    /// 用户登录请求命令处理类
    /// </summary>
    public class LoginUserHandler:IRequestHandler<LoginUserCommand,ApiResult<LoginDTO>>
    {
        IBaseRepository<UserModel> userRep;
        IBaseRepository<RoleModel> roleRep;
        IBaseRepository<UserRoleModel> userRoleRep;
        private readonly JwtTools JwtTools;
        private readonly IConfiguration configuration;

        public LoginUserHandler(IBaseRepository<UserModel> userRep, IBaseRepository<RoleModel> roleRep, IBaseRepository<UserRoleModel> userRoleRep, JwtTools JwtTools, IConfiguration configuration)
        {
            this.userRep = userRep;
            this.roleRep = roleRep;
            this.userRoleRep = userRoleRep;
            this.JwtTools = JwtTools;
            this.configuration = configuration;
        }

        public Task<ApiResult<LoginDTO>> Handle(LoginUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<LoginDTO> res = new ApiResult<LoginDTO>();
                var user=userRep.GetAll().Where(x=>x.UserName==request.userName&&!x.IsDeleted).FirstOrDefault();
                if (user==null)
                {
                    res.Msg = "用户不存在";
                    res.Code = ApiEnum.Fail;
                    return Task.FromResult(res);
                }
                request.password = request.password.GetMD5();
                if (user.Password != request.password)
                {
                    res.Msg = "密码不正确";
                    res.Code = ApiEnum.Fail;
                    return Task.FromResult(res);
                }
                var userrole=userRoleRep.GetAll().Where(x=>x.UserId==user.Id&&!x.IsDeleted).ToList();

                if(userrole.Count()==0)
                {
                    res.Msg = "尚未为此用户分配角色";
                    res.Code = ApiEnum.Fail;
                    return Task.FromResult(res);
                }
                var roleIds = new List<int>();
                var roles=new List<string>();

                foreach (var item in userrole)
                {
                    roleIds.Add(item.RoleId);
                    // 获取角色详细信息
                    var role = roleRep.GetAll()
                        .Where(x => x.Id == item.RoleId && !x.IsDeleted)
                        .FirstOrDefault();

                    if (role != null)
                    {
                        roles.Add(role.RoleName);
                    }
                }
                roles = roles.Distinct().ToList();
                var departments=userRep.GetAll().Where(x=>x.DepartmentId==user.DepartmentId && !x.IsDeleted).Select(x=>x.Id).ToList();
                var departmentids=new List<int>();
                foreach (var item in departments)
                {
                    var userid=userRep.GetAll().Where(x=>!x.IsDeleted&&x.Id==item).FirstOrDefault();
                    if(userid == null)
                    {
                        continue;
                    }
                    departmentids.Add(userid.Id);
                }
                departmentids = departmentids.Distinct().ToList();

                var managernames = new List<string>();
                foreach (var item in departmentids)
                {
                    var uid=userRep.GetAll().Where(x=>!x.IsDeleted&& x.Id==item&&x.IsManager==true).FirstOrDefault();
                    if (uid == null) { continue; }
                    managernames.Add(uid.UserName);
                }
                managernames = managernames.Distinct().ToList();

                var login = new LoginDTO
                {
                    Id = user.Id,
                    UserName = user.UserName,
                    RolesName = roles, // 逗号分隔的角色名称
                    RoleId = roleIds, // 角色ID列表
                    DepartmentId = user.DepartmentId,
                    DepartmentIds= departmentids,
                    ManagerName= managernames,
                    JwtToken= JwtTools.JwtNewString(configuration,user.Id.ToString())
                };
                res.Msg = "登录成功";
                res.Code = ApiEnum.Success;
                res.Data = login;
                return Task.FromResult(res);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
